#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
void *read(void *arg);
void *accu(void *arg);
static sem_t sem_one;
static sem_t sem_two;

int main(int argc, char **argv)
{
    sem_init(&sem_one, 0, 0);
    sem_init(&sem_two, 0, 1);
    pthread_t tid_1;
    pthread_t tid_2;
    int *num = new int(1);
    pthread_create(&tid_1, nullptr, read, (void *)num);
    pthread_create(&tid_2, nullptr, accu, (void *)num);
    pthread_join(tid_1, nullptr);
    pthread_join(tid_2, nullptr);
    return 0;
}
void *read(void *arg)
{
    int *num = (int *)arg;
    for (int i = 0; i < 5; i++)
    {
        printf("Input a number:");
        sem_wait(&sem_two);
        scanf("%d", num);
        sem_post(&sem_one);
    }
    return nullptr;
}

void *accu(void *arg)
{
    int *num = (int *)arg;
    int sum = 0;
    for (int i = 0; i < 5; i++)
    {
        sem_wait(&sem_one);
        sum += *num;
        sem_post(&sem_two);
    }
    printf("Resault: %d \n", sum);
    return nullptr;
}